<template>
  <el-card>
    <template #header>
      <el-button v-permissionBtn="`btn.Trademark.add`" type="primary" :icon="Plus" @click="showDialog">添加</el-button>
    </template>
    <el-table :data="trademarkList" border class="mb-10">
      <el-table-column label="序号" width="80" align="center" type="index"></el-table-column>
      <el-table-column label="品牌名称" prop="tmName"></el-table-column>
      <el-table-column label="品牌LOGO" prop="logoUrl">
        <template #default="{ row, $index }">
          <img :src="row.logoUrl" style="width: 80px;height: 80px;">
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="{row,$index}">
          <el-button  type="warning" :icon="Edit" @click="handleEdit(row,$index)">编辑</el-button>
           <el-button type="danger"  :icon="Delete" @click="handleDelete(row,$index)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination v-model:current-page="page" v-model:page-size="limit" :page-sizes="[3, 6, 9]"
      layout=" prev, pager, next, jumper,->, sizes,total," :total="total" @size-change="handleSizeChange"
      @current-change="handleCurrentChange" />

    <!-- form表单 -->
    <el-dialog
      v-model="dialogVisible"
      :title="tmForm.id ? '修改品牌':'添加品牌'"
      @close="cancelSave(ruleFormRef)"
    >

      <el-form 
        label-width="100px" 
        style="width: 500px;"  
        :model="tmForm"
        :rules="rules"
        ref="ruleFormRef"
      >

        <el-form-item label="品牌名称" prop="tmName">
          <el-input placeholder="请输入品牌名称" v-model="tmForm.tmName" ></el-input>
        </el-form-item>

        <el-form-item label="品牌LOGO" prop="logoUrl">
          <el-upload class="avatar-uploader" :action="uploadActions" :show-file-list="false"
            :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
            <img v-if="tmForm.logoUrl" :src="tmForm.logoUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
            <!-- <el-icon class="avatar-uploader-icon"><Plus /></el-icon> -->

            <template #tip>
              <div class="el-upload__tip">
                图片必须是JPG格式且不能大于2MB.
              </div>
            </template>

          </el-upload>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelSave(ruleFormRef)">取消</el-button>
          <el-button type="primary" @click="onSave(ruleFormRef)">
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>

  </el-card>
</template>

<script setup lang='ts'>
import { Delete, Edit, Plus } from "@element-plus/icons-vue";
import { onMounted, reactive, ref } from "vue";
import trademarkApi, { type TrademarkList, type TrademarkModel } from '@/api/trademark'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules, type UploadProps } from "element-plus";
import { cloneDeep } from "lodash";

const uploadActions = `${import.meta.env.VITE_API_URL}/admin/product/upload`

const dialogVisible = ref(false)  // 用于控制dialog显示与隐藏的变量


const showDialog = () => {   // 添加按钮的点击事件
  dialogVisible.value = true
}

const ruleFormRef = ref<FormInstance>()
// 表单校验
const rules = reactive<FormRules>({
  tmName: [
    { required: true, message: '请输入品牌名称', trigger: 'blur' },
    { min: 2, max: 10, message: '品牌名称最少2个字符最多10个字符', trigger: 'blur' },
  ],
  logoUrl: [
    { required: true, message: '请输入品牌LOGO', trigger: 'change'},
  ],
})


// 编辑的回调
const handleEdit = (row:TrademarkModel,index:number)=>{
  // 此处需要使用深拷贝，不然由于参数是地址，那么当更改后即使不点击保存，展示的数据也会实时变化，所以需要深拷贝
  tmForm.value = cloneDeep(row) 
  dialogVisible.value = true
}

// 删除的回调
const handleDelete = (row:TrademarkModel,index:number)=>{
  ElMessageBox.confirm(
    `确认删除[${row.tmName}]这个品牌吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then( async() => {
      // 点击确认的回调
      try {
        await trademarkApi.delete(row.id as number)
        ElMessage.success('删除成功')
        getPage()
      } catch (error) {
        ElMessage.error('删除失败，请重试')
      }
      
    })
    .catch(() => {
      // 点击取消的回调
    })
}

// 创建一个表单收集数据 -- 收集创建一个品牌的数据
const tmForm = ref<TrademarkModel>({
  tmName: '',
  logoUrl: ''
})


// 图片上传的回调
// 上传图片成功的回调
const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  tmForm.value.logoUrl = response.data
  // console.log(tmForm);

}

// 上传之前的回调,要进行拦截,不符合要求的图片拦截住
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('图片格式必须为JPG格式')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片大小不能超过2MB！')
    return false
  }
  return true
}

// 取消保存的回调
const cancelSave = (formEl:FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()   // 重置表单校验
  
  dialogVisible.value = false   // 关闭弹框
  tmForm.value = { tmName: '', logoUrl: '' }  // 重置表单数据
}
// 保存的回调
const onSave = async (formEl:FormInstance | undefined) => {
  if(!formEl) return

  formEl.validate(async (valid,fields)=>{
    // valid  布尔值 ，代表权限检验成功或者失败，true代表成功
    // fields 校验字段
    if (valid) {
      try {
        if (tmForm.value.id) {
          await trademarkApi.update(tmForm.value)  // 编辑保存
        }else{
          await trademarkApi.save(tmForm.value)  // 发送请求，保存品牌数据
        }

        ElMessage.success('保存成功')    // 提示用户保存成功
        cancelSave(formEl)    // 重置表单数据
        getPage() // 刷新页面
      } catch (error) {
        ElMessage.error('保存失败，请重试')
      }
    }
  })
 
}


// table展示的数据
const trademarkList = ref<TrademarkList>([])
// 获取分页数据
const getPage = async () => {
  try {
    let result = await trademarkApi.getPage(page.value, limit.value)
    // console.log('品牌分页数据',result);
    trademarkList.value = result.records
    total.value = result.total
  } catch (error) {
    ElMessage.error('获取品牌分页数据失败，请重试')
  }
}

onMounted(() => {
  getPage();
})

const page = ref(1)
const limit = ref(3)
const total = ref(0)


// 每页条数改变的回调
const handleSizeChange = (val: number) => {
  //函数体
  // 组装数据
  limit.value = val
  // 发送请求
  getPage()
}

const handleCurrentChange = (val: number) => {
  // 组装数据
  page.value = val
  // 发送请求
  getPage()

}
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>